﻿using CK.Sprite.CrossCutting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace CK.Sprite.StackExchangeRedis
{
    public static class ServiceCollectionRedisExtensions
    {
        public static IServiceCollection AddRedisCore(this IServiceCollection services)
        {
            var configuration = services.GetConfiguration();

            var redisEnabled = configuration["Redis:IsEnabled"];
            if (string.IsNullOrEmpty(redisEnabled) || bool.Parse(redisEnabled))
            {
                services.AddStackExchangeRedisCache(options =>
                {
                    var redisConfiguration = configuration["Redis:Configuration"];
                    if (!string.IsNullOrEmpty(redisConfiguration))
                    {
                        options.Configuration = redisConfiguration;
                    }
                });

                services.Replace(ServiceDescriptor.Singleton<IDistributedCache, SpriteRedisCache>());
            }

            return services;
        }

        public static void UseRedisCore(this IApplicationBuilder app)
        {
            app.ApplicationServices.GetService<IDistributedCache>();
        }
    }
}
